package com.bruce.tool.validate.hibernate.validator;

import com.bruce.tool.validate.hibernate.core.Validator;

import java.net.IDN;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 功能 :
 *
 * @author : Bruce(刘正航) 14:10 2019-04-12
 */
public class Email implements Validator<String> {

    private static final Pattern LOCAL_PART_PATTERN = Pattern.compile("[a-z0-9!#$%&'*+/=?^_`{|}~\u0080-\uffff-]+(\\.[a-z0-9!#$%&'*+/=?^_`{|}~\u0080-\uffff-]+)*", 2);
    private static final Pattern DOMAIN_PATTERN = Pattern.compile("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\]", 2);

    public static final String ERROR = "邮箱格式不对";

    @Override
    public boolean execute(String value) {
        if( null == value ){ return false; }
        if (value.length() != 0) {
            String[] emailParts = value.split("@", 3);
            if (emailParts.length != 2) {
                return false;
            } else {
                return !this.matchLocalPart(emailParts[0]) ? false : this.matchDomain(emailParts[1]);
            }
        } else {
            return true;
        }
    }

    private boolean matchLocalPart(String localPart) {
        if (localPart.length() > 64) {
            return false;
        } else {
            Matcher matcher = LOCAL_PART_PATTERN.matcher(localPart);
            return matcher.matches();
        }
    }

    private boolean matchDomain(String domain) {
        if (domain.endsWith(".")) {
            return false;
        } else {
            String asciiString;
            try {
                asciiString = IDN.toASCII(domain);
            } catch (IllegalArgumentException var4) {
                return false;
            }

            if (asciiString.length() > 255) {
                return false;
            } else {
                Matcher matcher = DOMAIN_PATTERN.matcher(asciiString);
                return matcher.matches();
            }
        }
    }
}
